package kr.ragne.letsparis;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Random;

import kr.ragne.framework.AppManager;
import kr.ragne.framework.Effect_Explosion;
import kr.ragne.framework.IState;
import kr.ragne.letsparissql.DBHelper;
import kr.ragne.letsparitime.R;
import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Handler;

public class GameState implements IState {
	public static final String TAG = "Collision";
	private Player player;
	private Enemy enem;
	private BackGround background;
	long startTime = 0;
	long playTime = 0;
	private Missile mis;
	private DBHelper helper;
	SoundPool mSoundPool;
	int sound_id1;
	MediaPlayer soundback;
	
	
	// 추가사항
	private int i, bulletCnt = 10; // 한 화면에 나올 총알 갯수
	
	int  timer = 0;
	Random rnd = new Random();
	
	ArrayList<Missile> enemmsList = new ArrayList<Missile>(); //	적의 미사일
	ArrayList<Effect_Explosion> expList = new ArrayList<Effect_Explosion>();	// 폭발애니

	public GameState(Activity context, DBHelper mHelper, MediaPlayer mSoundBackGround) {
		this.soundback = mSoundBackGround;
		AppManager.getInstance().gameState = this;
		this.helper = mHelper;
		mSoundPool = new SoundPool(5, AudioManager.STREAM_MUSIC,0);
		sound_id1 = mSoundPool.load(context, R.raw.teemo, 1);
		timer = 0;
	}
	
	public void MakeMissile(){
		
		if(System.currentTimeMillis() - playTime >= 1000){
			playTime = System.currentTimeMillis();
			for(i = 0; i <bulletCnt; i++){
				mis = new Missile_1(i, timer);
				mis.movetype = rnd.nextInt(8);
				mis.SetPosition(327, 242);
				enemmsList.add(mis);
			}
			
		}
	}
	
	@Override
	public void Init() {
		player = new Player(AppManager.getInstance().getBitmap(R.drawable.letspari));
		enem = new Enemy(AppManager.getInstance().getBitmap(R.drawable.parihell));
		background = new BackGround();
		
		AppManager.isFlag = true;
		AppManager.start = false;
		startTime = System.currentTimeMillis();
		
	}
	
	public Player getPlayer() {
		return player;
	}

	@Override
	public void Destroy() {
	}
	
	@Override
	public void Update() {
		if((AppManager.isFlag)){
			if (AppManager.start) {
				long gameTime = System.currentTimeMillis();
				player.Update(gameTime);
				enem.Update(gameTime + 5000);
				background.Update();

				for (int i = 0; i < enemmsList.size(); i++) {
					Missile enemms = enemmsList.get(i);
					enemms.Update(gameTime);
					if (enemms.state == Missile.STATE_OUT)
						enemmsList.remove(i);
				}
				for (int i = expList.size() - 1; i >= 0; i--) {
					Effect_Explosion exp = expList.get(i);
					exp.Update(gameTime);
					if (exp.getAniEnd())
						expList.remove(i);
				}
				MakeMissile();
				CheckCollision();
				
			}
		}
	}
	@Override
	public void Render(Canvas canvas) {
		background.Draw(canvas);
		Paint p = new Paint(Paint.ANTI_ALIAS_FLAG); // 검은색
		p.setColor(0xff000000);
		for(Effect_Explosion exp : expList){
			if(canvas != null) {
				exp.Draw(canvas);
			}
		}
		for(Missile enemms : enemmsList){
			enemms.Draw(canvas);
		}
		enem.Draw(canvas);
		player.Draw(canvas);
		Paint paint  = new Paint();
		paint.setTextSize(20);
		paint.setColor(Color.BLACK);
		if(AppManager.start){
			handler.postDelayed(r, 1000);
			canvas.drawText(timer/1000 + " : 초", 0, 20, paint);
		}
		
		if(AppManager.start == false){
			canvas.drawBitmap(AppManager.getInstance().getBitmap(R.drawable.gamestart), 0,0, p);
			startTime = System.currentTimeMillis();
		}
		
		if(AppManager.isFlag == false){
			canvas.drawBitmap(AppManager.getInstance().getBitmap(R.drawable.gameover), 0, 0, p);
		}
	}
	Handler handler = new Handler();
	Runnable r= new Runnable() {
		
		@Override
		public void run() {
			
			if((AppManager.isFlag)){
				if (AppManager.start) {
					timer = (int) (System.currentTimeMillis() - startTime);
					handler.postDelayed(this, 1000);
				}
			}
		}
	};
	
	
	public void CheckCollision(){
			for(int i = enemmsList.size()-1; i >= 0; i--){
				if(CollisionManager.CheckBoxToBox(player.boundBox, enemmsList.get(i).boundBox)){
					expList.add(new Effect_Explosion(player.getX(), player.getY()));
					enemmsList.removeAll(enemmsList);
					AppManager.isFlag = false;
					soundback.stop();
					mSoundPool.play(sound_id1, 50, 50, 0, 0, 1);
					// 점수 기록을 위해 데이터베이스 오픈
					SQLiteDatabase db = helper.getWritableDatabase();
					// 데이터베이스에 넣을 정보를 테이블 구조에 맞게 구성
					ContentValues row = new ContentValues();
					row.put("score", timer/1000);
					row.put("data", todayDate());
					db.insert("pari", null, row);
					db.close();
					
					return;
			}
		}
	}
	public static String todayDate() {
	      SimpleDateFormat formater = new SimpleDateFormat("yyyy/MM/dd",
	        Locale.KOREA);
	      Date current = new Date();
	      String date = formater.format(current);

	      Calendar cal = new GregorianCalendar();
	      int mHour = cal.get(Calendar.HOUR_OF_DAY);
	      int mMinute = cal.get(Calendar.MINUTE);
	      int mSecond = cal.get(Calendar.SECOND);

	      // yyyy-MM-dd HH:mm:ss.ms
	      String nowDate = date + " " + mHour + ":" + mMinute + ":" + mSecond;
	      return nowDate;
	     }
}
